<template>
  <div id="bar-chart" style="width: 390px; height: 300px"></div>
</template>

<script>
import * as echarts from "echarts";
import { getArea } from "@/api/system/info";

export default {
  name: "CameraEcharts",
  mounted() {
    getArea().then((res) => {
      if (res.code == 200) {
        //循环res.data获取camera_area 与 数量
        let area = [];
        let count = [];
        res.data.forEach((item) => {
          area.push(item.camera_area);
          count.push(item.count);
        });
        this.renderChart(area, count);
      }
    });
    // this.renderChart();
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeChart);
  },
  methods: {
    renderChart(area, count) {
      const chartDom = document.getElementById("bar-chart");
      this.myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: "摄像头位置统计",
          textStyle: {
            color: "#fff",
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        tooltip: {},
        xAxis: {
          type: "value",
          show: false,
        },
        grid: {
          left: "10px", // 增加左边距
          right: "10%",
          containLabel: true, // 确保轴标签在 grid 内
        },
        yAxis: {
          type: "category",
          data: area,
          axisLine: {
            show: false,
          },
          axisLabel: {
            fontSize: 12,
            fontWeight: "bold",
            overflow: "break",
            width: 200, // 增加宽度
            color: "#fff",
            interval: 0,
          },
        },
        series: [
          {
            type: "bar",
            data: count,
            barWidth: "50%",
            label: {
              show: true,
              position: "right",
              formatter: "{c}",
              color: "#FFFFFF",
            },
            itemStyle: {
              color: "#091A2CB5",
            },
          },
        ],
      };
      this.myChart.setOption(option);
    },
    resizeChart() {
      if (this.myChart) {
        this.myChart.resize();
      }
    },
  },
};
</script>

<style scoped>
#bar-chart {
  width: 100%;
  height: 100%;
}
</style>
